package cn.bjxy.shishaolong.system.file.controller;


import cn.bjxy.shishaolong.common.ResultMsg;
import cn.bjxy.shishaolong.common.StatusCode;
import cn.bjxy.shishaolong.common.SysConst;
import cn.bjxy.shishaolong.common.Utils;
import cn.bjxy.shishaolong.system.annotation.Permission;
import cn.bjxy.shishaolong.system.controller.AbstractController;
import cn.bjxy.shishaolong.system.file.entity.File;
import cn.bjxy.shishaolong.system.file.service.IFileService;
import cn.bjxy.shishaolong.utils.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.UpdateChainWrapper;
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.upload.FastFile;
import com.github.tobato.fastdfs.domain.upload.FastImageFile;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.Validate;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 文件 前端控制器
 * </p>
 *
 * @author 时少龙
 * @since 2019-03-21
 */
@RestController
@RequestMapping("/api/sys/file")
@PropertySource("classpath:config/system-config.properties")
@Slf4j
@Permission
public class FileController extends AbstractController {

    @Autowired
    private IFileService fileService;
    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FileUtil fileUtil;


    @PostMapping("/upload-image")
    public FileResult uploadImage(MultipartFile file) {
//        HashMap<String, Object> map = new HashMap<>();
        try {
            if (Objects.isNull(file)) {

            }
            // 1.上传
            File myFile = new File();
            StorePath storePath = storageClient.uploadImage(setFileInfo(file, myFile));

            // 2.保存结果
            String fullPath = storePath.getFullPath();
            myFile.setPath(fullPath);
            fileService.save(myFile);

            // 3.返回图片地址集
            FileResult fileResult = new FileResult();
            fileResult.setErrno(0);
            ArrayList<String> imagePathList = new ArrayList<>();
            imagePathList.add(fileUtil.generatorUrl(FileUtil.HTTP, fullPath));
            fileResult.setData(imagePathList);

            System.out.println("originalFileName" + file.getOriginalFilename());
            System.out.println("name:" + file.getName());
            System.out.println("contentType" + file.getContentType());
            System.out.println("" + file.getSize());

            return fileResult;
        } catch (Exception e) {
            e.printStackTrace();
            return new FileResult(-1, null);
        }
    }

    @PostMapping("/upload-file")
    public ResultMsg uploadFile(MultipartFile file) {
//        HashMap<String, Object> map = new HashMap<>();
        try {
            if (Objects.isNull(file)) {

            }
            // 1.上传
            File myFile = new File();
            StorePath storePath = storageClient.uploadFile(setFileInfoForFile(file, myFile));


            // 2.保存结果
            String fullPath = storePath.getFullPath();
            myFile.setPath(fullPath);
            fileService.save(myFile);

            // 3.返回图片地址集
//            FileResult fileResult = new FileResult();
//            fileResult.setErrno(0);
//            ArrayList<String> imagePathList = new ArrayList<>();
//            imagePathList.add("http://"+fastDfsServer + "/" + fullPath);
//            fileResult.setData(imagePathList);

            System.out.println("originalFileName" + file.getOriginalFilename());
            System.out.println("name:" + file.getName());
            System.out.println("contentType" + file.getContentType());
            System.out.println("" + file.getSize());

            return ResultMsg.success(myFile.setPath(fileUtil.generatorUrl(fileUtil.HTTP, myFile.getPath())));
        } catch (Exception e) {
            e.printStackTrace();
            return retOperatorFailure();
        }
    }

    /**
     * 设置文件信息，fastImageFile 和 数据库中存的文件信息
     *
     * @param multipartFile 上传的原始文件
     * @param myFile        数据库中存的文件信息
     * @throws IOException
     */
    private FastImageFile setFileInfo(MultipartFile multipartFile, File myFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String extType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String mime = multipartFile.getContentType();
        Set<MetaData> metaDataSet = new HashSet<>();
        metaDataSet.add(new MetaData("create_data",
                LocalDate.now().toString()));
        String fileName = originalFilename.substring(0,originalFilename.lastIndexOf("."));
        //设置本地上传文件信息
        myFile.setName(fileName).setType(extType).setMime(mime).setUpdatedAt(LocalDateTime.now());

        return new FastImageFile(multipartFile.getInputStream(), multipartFile.getSize(), extType, metaDataSet);
    }

    /**
     * 设置文件信息，fastImageFile 和 数据库中存的文件信息
     *
     * @param multipartFile 上传的原始文件
     * @param myFile        数据库中存的文件信息
     * @throws IOException
     */
    private FastFile setFileInfoForFile(MultipartFile multipartFile, File myFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String extType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String mime = multipartFile.getContentType();
        Set<MetaData> metaDataSet = new HashSet<>();
        metaDataSet.add(new MetaData("create_data",
                LocalDate.now().toString()));
        String fileName = originalFilename.substring(0,originalFilename.lastIndexOf("."));
        //设置本地上传文件信息
        myFile.setName(fileName).setType(extType).setMime(mime).setUpdatedAt(LocalDateTime.now());

        return new FastFile(multipartFile.getInputStream(), multipartFile.getSize(), extType, metaDataSet);
    }

    /**
     * 删除
     *
     * @param param
     * @return
     */
    @DeleteMapping("/delete")
    public ResultMsg delectFile(@RequestBody JSONObject param) {
        try {
            if (param == null || !param.containsKey(SysConst.ID)) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }
            String id = param.getString(SysConst.ID);
            File retFile = fileService.getById(id);
            if (retFile != null && !StringUtils.isEmpty(retFile.getPath())) {
                 storageClient.deleteFile(fileUtil.generatorUrl(fileUtil.HTTP,retFile.getPath()));
                fileService.removeById(id);
            }
            return ResultMsg.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.DELETE_FAILUER, StatusCode.DELETE_FAILUER_MSG);
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private class FileResult {
        private int errno;
        private List<String> data;
    }


}
